Categories
Material UI

Material UI — Snack Bars

Spread the love

Material UI is a Material Design library made for React.

It’s a set of React components that have Material Design styles.

In this article, we’ll look at how to add snack bars with Material UI.

Snackbar

Snack bars let us display messages about something happening in our app.

To create a simple one, we can use the Snackbar component.

For example, we can write:

import React from "react";
import Button from "@material-ui/core/Button";
import Snackbar from "@material-ui/core/Snackbar";
import IconButton from "@material-ui/core/IconButton";
import CloseIcon from "@material-ui/icons/Close";

export default function App() {
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true);
  };

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }

    setOpen(false);
  };

  return (
    <div>
      <Button onClick={handleClick}>Open snackbar</Button>
      <Snackbar
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left"
        }}
        open={open}
        autoHideDuration={6000}
        onClose={handleClose}
        message="hello world"
        action={
          <React.Fragment>
            <Button color="secondary" size="small" onClick={handleClose}>
              ok
            </Button>
            <IconButton size="small" color="inherit" onClick={handleClose}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </React.Fragment>
        }
      />
    </div>
  );
}

We created a snack bar with the message is set to 'hello world' .

And we have more content in the action prop.

They include a button that we can click and an IconButton to let us close the snack bar.

Customized Snack Bars

We can style snack bars with various styles.

To style it, we add the severity prop.

For instance, we can write:

import React from "react";
import MuiAlert from "@material-ui/lab/Alert";

function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}
export default function App() {
  return (
    <div>
      <Alert severity="error">error!</Alert>
      <Alert severity="warning">warning!</Alert>
      <Alert severity="info">info!</Alert>
      <Alert severity="success">success!</Alert>
    </div>
  );
}

Instead of using the Snackbar component, we used the Alert component instead.

It’s in the @material-ui/lab package instead of the @material-ui/core package.

Positioned Snack Bars

We can position the snack bar with the anchorOrigin prop.

To position it, we can write:

import React from "react";
import Snackbar from "@material-ui/core/Snackbar";
import Button from "@material-ui/core/Button";

export default function App() {
  const [state, setState] = React.useState({
    open: false,
    vertical: "top",
    horizontal: "center"
  });

  const { vertical, horizontal, open } = state;

  const handleClick = newState => () => {
    setState({ open: true, ...newState });
  };

  const handleClose = () => {
    setState({ ...state, open: false });
  };

  return (
    <div>
      <Button onClick={handleClick({ vertical: "top", horizontal: "center" })}>
        open
      </Button>

      <Snackbar
        anchorOrigin={{ vertical, horizontal }}
        open={open}
        onClose={handleClose}
        message="hello world"
      />
    </div>
  );
}

to set the position of the snack bar with the anchorOrigin prop.

It’s set to an object with the vertical and horizontal properties.

We set it to 'top' and 'center' respectively to show it at the top of the screen and centered.

Message Length

The width can vary in back bars.

We can write a long message by writing text in multiple lines:

import React from "react";
import Snackbar from "@material-ui/core/Snackbar";
import Button from "@material-ui/core/Button";

export default function App() {
  const [state, setState] = React.useState({
    open: false
  });

  const { open } = state;

  const handleClick = () => {
    setState({ open: true });
  };

  const handleClose = () => {
    setState({ ...state, open: false });
  };

  return (
    <div>
      <Button onClick={handleClick}>open</Button>

      <Snackbar
        open={open}
        onClose={handleClose}
        message={
          "Lorem ipsum dolor sit amet, consectetur adipiscing elit.
          Aenean mollis, metus vitae vestibulum suscipit, eros nisi ultrices urna."
        }
        action={
          <Button color="secondary" size="small">
            lorem ipsum dolorem
          </Button>
        }
      />
    </div>
  );
}

We have the message prop with a string expression that spans multiple lines but without line breaks.

Also, we have the action prop to show a button.

Conclusion

We can use snack bars to display different messages.

They can be styled and we can apply transitions to it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *